package ink.tiptop.common.worker.scan;


import ink.tiptop.utils.async.callback.ICallback;
import ink.tiptop.utils.async.callback.IWorker;
import ink.tiptop.utils.async.worker.WorkResult;
import ink.tiptop.utils.async.wrapper.WorkerWrapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author wuweifeng wrote on 2019-11-20.
 */
@Slf4j
public class ScanWorker implements IWorker<String, ScanResult>, ICallback<String, ScanResult> {

    private String localPath;
    private Pattern pattern;
    private Integer countDown;

    public ScanWorker( String localPath, Pattern pattern, Integer countDown) {
        this.localPath = localPath;
        this.pattern = pattern;
        this.countDown = countDown;
    }

    /**
     * @param object      object 这个是请求参数
     * @param allWrappers 任务包装
     * @return
     */
    @Override
    public ScanResult action(String object, Map<String, WorkerWrapper> allWrappers) {
        List<String> resultList = new ArrayList<>();
        // 这里用的递归,所以把list传进去
        deepInSearch(resultList, localPath);
        return new ScanResult(resultList);
    }
    /**
     * @param resultList
     * @param localPath
     * @return
     * 比如 countDown = 2
     * scan                 countDown 2 ✔
     *  ┣-scan1             countDown 1 ✔
     *  ┃ ┣-scan1.txt       countDown 0 ✔
     *  ┃ ┣-scan1-2         countDown 0 ✔
     *  ┃ ┃ ┗-scan1-2.txt   countDown -1 X
     *  ┃ ┣-scan1-3         countDown 0 ✔
     *  ┃ ┃ ┗-scan1-3.txt   countDown -1 X
     */
    private List<String> deepInSearch(List<String> resultList, String localPath ) {
        // 第一次 countDown 3
        //      文件夹 countDown 2
        File file = new File(localPath);
        if (file.isDirectory()) {
            // 如果是文件夹,则继续深度搜索
            for (File listedFile : file.listFiles()) {
                // 这个countDown--的位置很关键
                if (countDown > 0) {
                    countDown--;
                    deepInSearch(resultList, new File(localPath, listedFile.getName()).getAbsolutePath());
                }
            }
        } else {
            // 如果是文件,则比对 名称是否符合正则
            if (pattern.matcher(file.getName()).matches()) {
                if (file.getParent().endsWith("target")) {
                    // 在target目录下的才放进list
                    resultList.add(file.getAbsolutePath());
                }
            }
        }
        countDown++;
        return resultList;
    }



    @Override
    public ScanResult defaultValue() {
        return new ScanResult(new ArrayList<>());
    }

    @Override
    public void begin() {
        log.info("----开始执行异步扫描任务----");
    }

    @Override
    public void result(boolean success, String param, WorkResult<ScanResult> workResult) {
        log.info("----执行异步扫描任务完成----");
    }

}
